package com.efuture.servlet.simplelogindemo.servlet;

import com.efuture.servlet.simplelogindemo.dao.UserDao;
import com.efuture.servlet.simplelogindemo.domian.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @description:
 * @author zhaoshanshan
 * @date 2021/10/3 1:02 上午
 * @version 1.0
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        User loginUser = new User();
//        if(null==request.getParameter("username")||null==request.getParameter("username")){
//            request.getRequestDispatcher("/FailLoginServlet").forward(request,response);
//            return;
//        }
//        loginUser.setUserName(request.getParameter("username"));
//        loginUser.setPassWord(request.getParameter("password"));
        Map<String, String[]> parameterMap = request.getParameterMap();
        try {
            BeanUtils.populate(loginUser,parameterMap);//
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            request.getRequestDispatcher("/FailLoginServlet").forward(request,response);
            return;
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            request.getRequestDispatcher("/FailLoginServlet").forward(request,response);
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.login(loginUser);
        if(null!=user){
            //成功
            request.setAttribute("userName",user.getUsername());
            request.getRequestDispatcher("/SuccessLoginServlet").forward(request,response);
        }else{
            //失败
            request.getRequestDispatcher("/FailLoginServlet").forward(request,response);
        }
    }
}
